package dev.caobaoqi6040.backend.modules.user.controller;

import dev.caobaoqi6040.backend.infrastructure.cache.service.UserAuthTokenCacheService;
import dev.caobaoqi6040.backend.infrastructure.security.jwt.Jwt;
import dev.caobaoqi6040.backend.modules.user.domain.request.SignInVo;
import dev.caobaoqi6040.backend.modules.user.domain.request.SignUpVo;
import dev.caobaoqi6040.backend.modules.user.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;

/**
 * AuthController
 *
 * @author caobaoqi6040
 * @since 2025/10/9 14:58
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/auth")
public class AuthController {

	private final Jwt jwt;
	private final AuthService service;
	private final UserAuthTokenCacheService userAuthTokenCacheService;

	@PostMapping("/sign-in")
	public ResponseEntity<String> signIn(HttpServletRequest request, HttpServletResponse response,
										 @RequestBody @Valid SignInVo vo) {
		service.signIn(vo.email(), vo.password());
		String token = jwt.makeToken(request, response, vo.email());
		userAuthTokenCacheService.upsertInfo(vo.email(), token);
		log.debug("[AuthController.signIn | cache ] put for {}", vo.email());
		return ResponseEntity.ok(token);
	}

	@PostMapping("/sign-up")
	public ResponseEntity<Void> signup(@RequestBody @Valid SignUpVo vo) {
		// TODO("add verify code logic")
		service.signup(vo.email(), vo.password());
		return ResponseEntity.created(URI.create("api/v1/user/" + vo.email())).build();
	}

}
